#include "qbattery.h"
#include <QPainter>
#include <QFontMetrics>

QBattery::QBattery(QWidget *parent) :
    QWidget(parent)
{
}

void QBattery::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter(this);
    QRect rect(0, 0, this->width(), this->height());
    painter.setViewport(rect);
    painter.setWindow(0, 0, 120, 50);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setRenderHint(QPainter::TextAntialiasing);
    //绘制电池边框
    QPen pen;
    pen.setWidth(2);
    pen.setColor(mColorBoder);
    pen.setStyle(Qt::PenStyle::SolidLine);
    pen.setCapStyle(Qt::PenCapStyle::FlatCap);
    pen.setJoinStyle(Qt::PenJoinStyle::BevelJoin);
    painter.setPen(pen);
    //设置笔画
    QBrush brush;
    brush.setColor(mColorBack);
    brush.setStyle(Qt::BrushStyle::SolidPattern);
    painter.setBrush(brush);
    //电池边框
    rect.setRect(1, 1, 109, 48);
    painter.drawRect(rect);
    //电池头
    brush.setColor(mColorBoder);
    painter.setBrush(brush);
    rect.setRect(110, 15, 10, 20);
    painter.drawRect(rect);
    //电池颜色
    if (mPowerLevel > mWarningLevel) {
        brush.setColor(mColorPower);
        pen.setColor(mColorPower);
    }
    else {
        brush.setColor(mColorWarning);
        pen.setColor(mColorWarning);
    }
    painter.setBrush(brush);
    painter.setPen(pen);
    if (mPowerLevel > 0) {
        rect.setRect(5, 5, mPowerLevel, 40);
        painter.drawRect(rect);
    }
    //绘制文字
    QFontMetrics textSize(this->font());
    QString powStr = QString::asprintf("%d%%", mPowerLevel);
    QRect textRect = textSize.boundingRect(powStr);
    painter.setFont(this->font());
    pen.setColor(mColorBoder);
    painter.setPen(pen);
    painter.drawText(55 - textRect.width() / 2,
                     23 +textRect.height() / 2,
                     powStr);
}

void QBattery::setPowerLevel(int power)
{
    mPowerLevel = power;
    emit powerLevelChanged(power);
    repaint();
}

int QBattery::getPowerLevel() const
{
    return mPowerLevel;
}

void QBattery::setWaringLevel(int warning)
{
    mWarningLevel = warning;
    repaint();
}

int QBattery::getWaringLevel() const
{
    return mWarningLevel;
}

QSize QBattery::getSizeHint() const
{
    return this->size();
}
